/*
 * 文件名：DbManager.java
 * 版权：Copyright by will_awoke
 * 描述：
 * 修改人：lyh
 * 修改时间：2013-10-15
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.qbgs.util;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.qbgs.constant.SystemConfig;


/**
 * JDBC 处理类
 * @author lyh
 * @version 2013-10-15
 * @see DbManager
 * @since
 */
public class DbManager
{
    /**
     * 日志
     */
    private static final Logger LOGGER = Logger.getLogger(DbManager.class);

    /**
     * 命名上下文
     */
    private static Context initctx = null;

    /**
     * 数据源
     */
    private static DataSource bds = null;

    /**
     * jndi名称
     */
    private static String jndiName = "";

    static
    {
        jndiName = SystemConfig.JDBC_JNDI_NAME;
        init();
    }

    /**
     * 
     * Description: 获得DB连接<br>
     * @return 
     * @see
     */
    public static Connection getDBConnection()
    {
        // for jndi
        Connection con = null;
        try
        {
            con = bds.getConnection();
        }
        catch (SQLException e)
        {
            LOGGER.error(e);
        }
        return con;
    }

    /**
     * 
     * Description:关闭DB连接 <br>
     * @param con 
     * @see
     */
    public static void closeDBConnection(Connection con)
    {
        try
        {
            if (con != null && !con.isClosed())
            {
                con.close();
            }
        }
        catch (Exception e)
        {
            LOGGER.error(e);
        }
    }

    /**
     * 关闭rs,statement,conn资源 <br>
     * 另可参看：org.apache.commons.dbutils.DbUtils 类设计 <br>
     * @param con 
     * @see
     */
    public static void closeJDBCResource(ResultSet rs, Statement st, Connection con)
    {
        try
        {
            if (rs != null && !rs.isClosed())
            {
                rs.close();
            }
            if (st != null && !st.isClosed())
            {
                st.close();
            }
            if (con != null && !con.isClosed())
            {
                con.close();
            }
        }
        catch (SQLException ex)
        {
            LOGGER.error(ex);
        }

    }

    /**
     * 
     * Description:jndi init method <br>
     * @see
     */
    private static void init()
    {
        try
        {
            initctx = new InitialContext();
            bds = (DataSource)initctx.lookup(jndiName);
        }
        catch (Exception e)
        {
            LOGGER.error(e);
        }
    }
}